var express = require('express');
var router = express.Router();
const fs=require('fs')
const path =require('path')

/*
* @desc
* 读取  upload文件夹的所有图标 名称
* */
let dirs = [];
async function readDirName() {
    var ignoresList = ['package.json', 'app.js', 'node_modules', 'xiaoguayun-icon.zip', 'package-lock.json', 'package.json', 'pm2.config.js']
    var path = require("path");
    var fs = require("fs");
    var pathName = path.resolve(__dirname, "../upload")
    var results = await fs.readdirSync(pathName);
    var files = results
    for (var i = 0; i < files.length; i++) {
        var isContain = ignoresList.some(_item => _item == files[i]);
        if (!isContain) {
            var result = await fs.statSync(path.join(pathName, files[i]))
            if (result.isFile()) {
                dirs.push(files[i]);
            }
        }

    }
    /*    console.log(dirs);*/
    return dirs
}


router.get('/', async function (req, res, next) {
    var dirs = await readDirName();
    console.log('dirs', dirs)
    res.render('index', {
        title: 'Express', dirs,
        host_name:process.env.HOST_NAME
    });
});


//处理文件夹上传
var multer  = require('multer');
var upload = multer({dest: 'upload_tmp/'});
router.post('/api/uploadImage', upload.any(),async function (req, res, next) {
    //上传的图片写道 /upload文件夹下
    var file=req.files[0]
    var fileName=file.originalname
    //如果文件夹名称冲突 不执行
    if(dirs.filter(name=>name==fileName)[0]){
        res.send({code:1,msg:`文件名称【${fileName}】冲突`})
        return  false;
    }
    fs.writeFileSync(path.resolve(__dirname,`../upload/${fileName}`),fs.readFileSync( file.path))
    fs.unlink(path.resolve(__dirname,`../${file.path}`),(e)=>{
        console.log(e)
    })
    //重新跟新界面
    readDirName()

    res.send({code:0,msg:'上传成功'})
});

router.get('/test', async function (req, res, next) {
    res.render('test', {title: 'Express'});
});



module.exports = router;
